<?php

namespace App\Admin\Controllers;

use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use App\Admin\Models\Income;
use App\Services\Common;
use App\Services\Distribution;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Alert;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Callout;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\InfoBox;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Echarts\Echarts;
use Illuminate\Http\Request;
use DB;

class StatisticsController extends Controller
{
    public function newUsers(Content $content){

    	$content->row(function ($row) {
    		$grid = new Grid(new Temp);

			$grid->filter(function($filter){

			    // 去掉默认的id过滤器
			    $filter->disableIdFilter();

			    $filter->column(1/2, function ($filter) {

			    	$formartData = array();
			    	$formartData[1] = '金拱门';
			    	$formartData[2] = '开封菜';

				    $filter->equal('shop_name', '商家名称')->select($formartData);
				    $filter->like('user_name', '用户姓名');
				});

				$filter->column(1/2, function ($filter) {
				    $filter->like('order_id', '订单号');
				    $filter->between('pay_time', '下单时间')->datetime();
				});

			});

			// 获取当前行数据
			$grid->actions(function ($actions) {

			    $actions->disableDelete();
			    $actions->disableEdit();
			    $actions->disableView();
			});

			// 禁用创建按钮
			$grid->disableCreateButton();

			// 默认展开筛选框
//			$grid->expandFilter();

			// 禁用行选择checkbox
			$grid->disableRowSelector();

			// 禁用导出数据按钮
			$grid->disableExport();

			// 禁用行操作列
			$grid->disableActions();

			// 禁用分页条
			$grid->disablePagination();
			// 禁用过滤器 刷新，筛选，列选择按钮
//			$grid->disableTools();
			// 禁用列选择器
			$grid->disableColumnSelector();

            $row->column(12, $grid); // 标题，图标，颜色，链接，数量


            $json = "option = {
    title : {
        text: '日新增用户和新增消费用户',
        subtext: ''
    },
    tooltip : {
        trigger: 'axis'
    },
    legend: {
        data:['新增用户','新增消费用户']
    },
    toolbox: {
        show : true,
        feature : {
            dataView : {show: true, readOnly: false},
            magicType : {show: true, type: ['line', 'bar']},
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },
    calculable : true,
    xAxis : [
        {
            type : 'category',
            data : ['1号','2号','3号','4号','5号','6号','7号','8号','9号','10号','11号','12号']
        }
    ],
    yAxis : [
        {
            type : 'value'
        }
    ],
    series : [
        {
            name:'新增用户',
            type:'bar',
            data:[20, 49, 70, 232, 256, 767, 1356, 1622, 326, 200, 64, 33],
            markPoint : {
                data : [
                    {type : 'max', name: '最大值'},
                    {type : 'min', name: '最小值'}
                ]
            },
            markLine : {
                data : [
                    {type : 'average', name: '平均值'}
                ]
            }
        },
        {
            name:'新增消费用户',
            type:'bar',
            data:[26, 59, 90, 264, 287, 707, 1756, 1822, 487, 188, 60, 23],
            markPoint : {
                data : [
                    {name : '年最高', value : 1822, xAxis: 7, yAxis: 183},
                    {name : '年最低', value : 23, xAxis: 11, yAxis: 3}
                ]
            },
            markLine : {
                data : [
                    {type : 'average', name : '平均值'}
                ]
            }
        }
    ]
};
";


			$echarts = new Echarts('新增用户', '新增用户日分布');
			$echarts->setStyle('height:450px;width:100%;');
			$echarts->setDirectJson($json);

            $row->column(12, new Box('新增用户', $echarts));
        });

		$content->header('新增用户统计');
        $content->description('新增用户分布');

        return $content;
    }

    // 获取日流水
    public function getDayAccount(Content $content, Request $request){

    	$sId = $request->input('sId');
    	$date = $request->input('date');
    	$objId = $request->input('objId');

    	$sql = "SELECT
	wt.*
FROM
	wallet_trade AS wt
LEFT JOIN wallet_account AS wa ON wt.waId = wa.waId
WHERE
	wa.uId = ?
AND wt.wcusId = ?
AND wt.createTime >= ?
AND wt.createTime < date_add(?, INTERVAL 1 DAY)
ORDER BY wtId;";

    	$content->title($date.'日账本');

		// 使用列
		$utilize = ['wtId', 'wtChangedMoney', 'wtAbstract', 'wtCurrentMoney',
						'wtCost', 'wtProfit', 'createTime', 'createUser'];

	    $showTable = $this->getTableData($sql, [$objId, $sId, $date, $date], $utilize);

//print_r($showTable);exit;
        // table 1
        $headers = ['Id', '金额', '交易摘要', '记账前账户金额', '成本', '利润', '创建时间', '创建人'];
        $rows = $showTable;

        $table1 = new Table($headers, $rows);

        $content->row((new Box('账本列表', $table1))->style('primary')->solid());

        return $content;
    }

    // 获取日流水
    public function getDayRecharge(Content $content, Request $request){

        $sId = $request->input('sId');
        $date = $request->input('date', date('Y-m-d'));
        $objId = $request->input('objId');
        $dayStart = date("Y-m-d 00:00:00");
        $dayEnd = date("Y-m-d 23:59:59");

        $sql = "select tmp.*,u.muNickName from(SELECT c.wcusId,c.wcCash,c.createTime,a.uId FROM wallet_charge as c
LEFT JOIN wallet_account as a
ON c.waId = a.waId 
where c.wcusId={$sId} and c.wcObj='recharge' 
and c.createTime between '{$dayStart}' and '{$dayEnd}') as tmp , member_users as u
where tmp.uId = u.muCode";
//echo $sql;exit;
        $content->title($date.'日充值');

        // 使用列
        $utilize = ['muNickName', 'wcCash', 'createTime'];

        $showTable = $this->getTableData($sql, [], $utilize);

//print_r($showTable);exit;
        // table 1
        $headers = ['姓名', '金额', '时间'];
        $rows = $showTable;

        $table1 = new Table($headers, $rows);

        $content->row((new Box('充值列表', $table1))->style('primary')->solid());

        return $content;
    }

    // 获取日办卡清单
    public function getDayCard(Content $content, Request $request){

    	$sId = $request->input('sId');
    	$date = $request->input('date');

    	$sql = "SELECT
	sgo.*, sg.sgName, mu.muNickName
FROM
	store_goods_out AS sgo
LEFT JOIN store_goods AS sg ON sgo.sgId = sg.sgId
LEFT JOIN member_users AS mu ON sgo.muId = mu.muCode
WHERE
	sgo.sId = ?
AND sgo.createTime >= ?
AND sgo.createTime < date_add(?, INTERVAL 1 DAY)
AND sg.sgIsTimeCard = 1
ORDER BY sgo.createTime DESC";

    	$content->title($date.'日售卖清单');

		// 使用列
		$utilize = ['sgoId', 'sgName', 'muNickName', 'sgoSaleNum', 'sgoSalePrice', 'sgoMemo', 'createTime', 'createUser'];

	    $showTable = $this->getTableData($sql, [$sId, $date, $date], $utilize);

//print_r($showTable);exit;
        // table 1
        $headers = ['Id', '卡项', '购买人', '数量', '金额', '备注', '创建时间', '创建人'];
        $rows = $showTable;

        $table1 = new Table($headers, $rows);

        $content->row((new Box('售卖清单', $table1))->style('warning')->solid());

        return $content;
    }

   	// 获取日耗卡清单
    public function getDayUseCard(Content $content, Request $request){

    	$sId = $request->input('sId');
    	$date = $request->input('date');

    	$sql = "SELECT
	scl.*, mu.muNickName, au.username, sg.sgName, smc.smcCanUseNum
FROM
	store_cards_log AS scl
LEFT JOIN member_users AS mu ON scl.muCode = mu.muCode
LEFT JOIN admin_users AS au ON scl.auCode = au.auCode
LEFT JOIN store_goods AS sg ON scl.sgId = sg.sgId
LEFT JOIN store_member_cards AS smc ON scl.smcId = smc.smcId
WHERE
	scl.sId = ?
AND scl.createTime >= ?
AND scl.createTime < date_add(?, INTERVAL 1 DAY)";

    	$content->title($date.'日耗卡清单');

		// 使用列
		$utilize = ['sgoId', 'sgName', 'sclUseNum', 'muNickName', 'username', 'smcCanUseNum', 'createTime', 'createUser'];

	    $showTable = $this->getTableData($sql, [$sId, $date, $date], $utilize);

//print_r($showTable);exit;
        // table 1
        $headers = ['Id', '卡项', '使用次数', '客户姓名', '服务店员姓名', '卡项剩余次数', '创建人', '创建时间'];
        $rows = $showTable;

        $table1 = new Table($headers, $rows);

        $content->row((new Box('耗卡清单', $table1))->style('warning')->solid());

        return $content;
    }

    // 获取新增会员
    public function getDayAddMember(Content $content, Request $request){

    	$sId = $request->input('sId');
    	$date = $request->input('date');

    	$sql = "SELECT *, al.alName, CASE WHEN muSex=0 THEN '女' ELSE '男' END AS muSex
FROM member_users AS mu  
LEFT JOIN agency_level AS al ON mu.alId = al.alId
WHERE
	mcId = ?
AND mu.createTime >= ?
AND mu.createTime < date_add(?, INTERVAL 1 DAY)";

    	$content->title($date.'日新增会员');

		// 使用列
		$utilize = ['muId', 'muNickName', 'muSex', 'muMobile', 'alName', 'muMemo', 'createUser', 'createTime'];

	    $showTable = $this->getTableData($sql, [$sId, $date, $date], $utilize);

//print_r($showTable);exit;
        // table 1
        $headers = ['Id', '姓名', '性别', '电话', '等级', '备注', '创建人', '创建时间'];
        $rows = $showTable;

        $table1 = new Table($headers, $rows);

        $content->row((new Box('新增会员', $table1))->style('info')->solid());

        return $content;
    }

    // 获取流水月统计
    public function getMonthAccount(Request $request){

    	$sId = $request->input('sId');
    	$date = $request->input('date');
    	$objId = $request->input('objId');

    	$sql = "SELECT
	*
FROM
	stats_day AS sd
WHERE
	scId = ?
AND DATE_FORMAT(sdDay, '%Y-%m') = ?
AND sdName = 'flowAccount'
AND sdObjId = ?";

		$list = DB::select($sql, [$sId, $date, $objId]);

		$eventData = array();
		foreach($list as $info){
			$eventObj = array();
			$eventObj['title'] = '流水：'.$info->sdValue;
			$eventObj['start'] = $info->sdDay;
			$eventObj['url'] = route("getDayAccount")."?sId={$sId}&date={$info->sdDay}&objId={$objId}";
			$eventObj['backgroundColor'] = '#f56954'; //red
        	$eventObj['borderColor'] = '#f56954'; //red
        	array_push($eventData, $eventObj);
		}

		$url = route("getDayAccount")."?sId={$sId}&objId={$objId}";
		$dataCost = $this->getMonthStats($sId, $date, 'cost', $objId, $url, '成本：', '#f39c12');
		$dataProfit = $this->getMonthStats($sId, $date, 'profit', $objId, $url, '利润：', '#0073b7');

		$eventData = array_merge($eventData, $dataCost, $dataProfit);

		return $eventData;
    }

    // 获取月每天充值记录
    public function getMonthRecharge(Request $request){

        $sId = $request->input('sId');
        $date = $request->input('date',date('Y-m'));
        $objId = $request->input('objId');

        $sql = "select tmp.*,u.muRealName,sum(tmp.wcCash) as money 
from(SELECT c.wcusId,c.wcCash,left(c.createTime,10) as day,a.uId 
FROM wallet_charge as c LEFT JOIN wallet_account as a ON c.waId = a.waId 
where c.wcusId={$sId} and c.wcObj='recharge' and DATE_FORMAT(c.createTime, '%Y-%m') = '{$date}' ) as tmp , 
member_users as u where tmp.uId = u.muCode group by tmp.day";

        $list = DB::select($sql, []);

        $eventData = array();
        foreach($list as $info){
            $eventObj = array();
//            $tmp = substr($info->createTime, 0, 10);
            $eventObj['title'] = '金额：'.$info->money;
            $eventObj['start'] = $info->day;
            $eventObj['url'] = route("getDayRecharge")."?sId={$sId}&date={$info->day}&objId={$objId}";
            $eventObj['backgroundColor'] = '#f56954'; //red
            $eventObj['borderColor'] = '#f56954'; //red
            array_push($eventData, $eventObj);
        }

//        $url = route("getDayAccount")."?sId={$sId}&objId={$objId}";
//        $dataCost = $this->getMonthStats($sId, $date, 'cost', $objId, $url, '成本：', '#f39c12');
//        $dataProfit = $this->getMonthStats($sId, $date, 'profit', $objId, $url, '利润：', '#0073b7');
//
////        $eventData = array_merge($eventData, $dataCost, $dataProfit);

        return $eventData;
    }

    // 获取月统计
    private function getMonthStats($sId, $date, $sdName, $sdObjId, $lowerUrl, $title="", $color="#f56954"){

    	$sql = "SELECT
	*
FROM
	stats_day AS sd
WHERE
	scId = ?
AND DATE_FORMAT(sdDay, '%Y-%m') = ?
AND sdName = ?
AND sdObjId = ?";

		$list = DB::select($sql, [$sId, $date, $sdName, $sdObjId]);

		$eventData = array();
		foreach($list as $info){
			$eventObj = array();
			$eventObj['title'] = $title.$info->sdValue;
			$eventObj['start'] = $info->sdDay;
			$eventObj['url'] = $lowerUrl."&date={$info->sdDay}";
			$eventObj['backgroundColor'] = $color;
        	$eventObj['borderColor'] = $color;
        	array_push($eventData, $eventObj);
		}

		return $eventData;
    }

    //public function get

    public function showCalendar(Content $content, Request $request){

    	$type = $request->input('type');
    	$sId = $request->input('sId');
    	$objId = $request->input('objId');

    	if ($type == 'account'){
    		$url = route('getMonthAccount')."?sId={$sId}&objId={$objId}";
    	} else if ($type == 'card'){

    	} else if ($type == 'rechargeDay'){
            $url = route('getDayRecharge')."?sId={$sId}&objId={$objId}";
        } else if ($type == 'rechargeMonth'){
            $url = route('getMonthRecharge')."?sId={$sId}&objId={$objId}";
        }

    	$viewData = array();
    	$viewData['url'] = $url;
    	//return view('admin.calendar', $viewData);

//  	Admin::css(asset("fullcalendar-4.2.0/packages/core/main.css"));
//  	Admin::css(asset("fullcalendar-4.2.0/packages/daygrid/main.css"));
//  	Admin::js(asset("fullcalendar-4.2.0/packages/core/main.js"));
//  	Admin::js(asset("fullcalendar-4.2.0/packages/interaction/main.js"));
//  	Admin::js(asset("fullcalendar-4.2.0/packages/daygrid/main.js"));
//  	Admin::js(asset("fullcalendar-4.2.0/packages/core/locales/zh-cn.js"));
    	Admin::disablePjax();

    	$content->view('admin.calendar', $viewData);

    	return $content;
    }

    private function getTableData($sql, $paramArray = [], $utilizeArray){

    	$list = DB::select($sql, $paramArray);

    	$showTable = array();

    	foreach($list as $info){
    		$newAttributes = array();
    		foreach($utilizeArray as $column){
		    	foreach($info as $key => $value){
					if ($key == $column){
						$newAttributes[$key] = $value;
					}
			    }
		    }
		    array_push($showTable, $newAttributes);
	    }

	    return $showTable;
    }

    // 获取月统计日历数据
    public function getCalendarData(Request $request){

    	$sId = $request->input('sId');
    	$date = $request->input('date');
    	$objId = $request->input('objId');
    	$target = $request->input('target');

    	$title = "";
    	$color = "#f56954";
    	if ($target == "account"){

    	}else if ($target == "cost"){
    		$title = "成本：";
    		$color = "#f56954";
    	}else if ($target == "profit"){
    		$title = "利润：";
    		$color = "#f56954";
    		$lowerUrl = '';
    	}else if ($target == ""){

    	}else if ($target == ""){

    	}else if ($target == ""){

    	}else if ($target == ""){

    	}
    	$data = $this->getMonthStats($sId, $date, $target, $objId, $lowerUrl, $title, $color);

    	return $data;
    }
    
    public function incomeTypeList(Request $request, Content $content){
    	
    	$grid = new Grid(new Income);
        $grid->incomeDay('日期');
        $grid->incomeCash('收入现金');
        $grid->incomeAlipay('收入支付宝');
        $grid->incomeWx('收入微信');

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});
		
		$grid->actions(function ($actions) {
		    $actions->disableDelete();
		    $actions->disableEdit();
		    $actions->disableView();
		});
		
		// 禁用行操作列
		$grid->disableActions();

		// 禁用创建按钮
		$grid->disableCreateButton();

		// 禁用查询过滤器
		$grid->disableFilter();

		// 默认展开筛选框
//		$grid->expandFilter();
		
		// 禁用行选择checkbox
		$grid->disableRowSelector();
		
		// 禁用导出
		$grid->disableExport();
        
        return $content
            ->header('每日支付方式统计')
            ->description('列表')
            ->body($grid);
    }
    
    public function getDisStatsList(Request $request, Content $content){
    	
    	$currentYear = date('Y', time());
    	$currentMonth = date('m', time());
    	$year = $request->input('year', $currentYear);
    	$month = $request->input('month', $currentYear.'-'.$currentMonth);
    	$userCode = $request->input('userCode');

		$Common = new Common();
    	$Distribution = new Distribution();
    	
    	$beginMonth = $currentYear.'-01';
    	$endMonth = $currentYear.'-12-31 23:59:59';

		//////////////////////////////////////////////////////////////////////////////////////
    	$yearList = array();
    	for($startYear=2019;$startYear<=$currentYear;$startYear++){
    		array_push($yearList, $startYear);
    	}
    	
    	$yearSelectHtml = '<div class="col-md-4">';
		$yearSelectHtml = $yearSelectHtml.'    <div class="form-group">';
		$yearSelectHtml = $yearSelectHtml.'        <label>选择年份</label>';
		$yearSelectHtml = $yearSelectHtml.'        <select id="disYear" class="form-control select2" style="width: 100%;">';
		foreach($yearList as $seletYear){
			if ($seletYear == $year){
				$yearSelectHtml = $yearSelectHtml.'            <option value="'.$seletYear.'" selected="selected">'.$seletYear.'</option>';
			}else{
				$yearSelectHtml = $yearSelectHtml.'            <option value="'.$seletYear.'">'.$seletYear.'</option>';
			}
		}
		$yearSelectHtml = $yearSelectHtml.'        </select>';
		$yearSelectHtml = $yearSelectHtml.'    </div>';
		$yearSelectHtml = $yearSelectHtml.'</div>';

    	//////////////////////////////////////////////////////////////////////////////////////
    	//////////////////////////////////////////////////////////////////////////////////////
    	$monthList = array();
    	for($selMonth=1;$selMonth<=12;$selMonth++){
    		$tmpMonth = $selMonth<10?'0'.$selMonth:$selMonth;
    		array_push($monthList, $tmpMonth);
    	}
    	
    	$monthSelectHtml = '<div class="col-md-4">';
		$monthSelectHtml = $monthSelectHtml.'    <div class="form-group">';
		$monthSelectHtml = $monthSelectHtml.'        <label>选择月份</label>';
		$monthSelectHtml = $monthSelectHtml.'        <select id="disMonth" class="form-control select2" style="width: 100%;">';
		foreach($monthList as $seletMonth){
//			print_r($year.'-'.$seletMonth.'月');print_r('|');print_r($month.'月');exit;
			if ($year.'-'.$seletMonth.'月' == $month.'月'){
				$monthSelectHtml = $monthSelectHtml.'            <option value="'.$seletMonth.'" selected="selected">'.$seletMonth.'月</option>';
			}else{
				$monthSelectHtml = $monthSelectHtml.'            <option value="'.$seletMonth.'">'.$seletMonth.'月</option>';
			}
		}
		$monthSelectHtml = $monthSelectHtml.'        </select>';
		$monthSelectHtml = $monthSelectHtml.'    </div>';
		$monthSelectHtml = $monthSelectHtml.'</div>';

		//$content->row($yearSelectHtml);
		$content->row($yearSelectHtml.' '.$monthSelectHtml);
		
		$thisUrl = route('getDisStatsList').'?userCode='.$userCode;
		//////////////////////////////////////////////////////////////////////////////////////
		$script = <<<EOT

	$("#disYear").change(function(){
		//alert($("#disYear").val())
		var year = $("#disYear").val();
		var month = $("#disYear").val() + "-" + $("#disMonth").val();
		window.location.href = "{$thisUrl}&year="+year+"&month="+month
	});
	
	$("#disMonth").change(function(){
		//alert($("#disMonth").val())
		var year = $("#disYear").val();
		var month = $("#disYear").val() + "-" + $("#disMonth").val();
		window.location.href = "{$thisUrl}&year="+year+"&month="+month
	});

EOT;
			Admin::script($script);
		
    	//////////////////////////////////////////////////////////////////////////////////////
    	$sId = Admin::user()->sId;
    	
    	$selfInfo = $Common->getUserInfoWithCache($sId, $userCode);
    	
    	$disMonthCount = $Distribution->getDisMonthCount($sId, $userCode, $beginMonth, $endMonth);
//  	print_r($disMonthCount);exit;
    	$monthArrayStr = "";

    	for($i=1;$i<=12;$i++){
    		$tempMonth = $i<10?'0'.$i.'月':$i.'月';
    		$tempMonth = '"'.$tempMonth.'"';
    		$monthArrayStr = $monthArrayStr.','.$tempMonth;
    	}
    	$monthArrayStr = substr($monthArrayStr, 1);
    	
    	$monthDataStr = "";
    	$disTotalMoney = 0;
    	foreach($disMonthCount as $disMonthInfo){
    		$monthDataStr = $monthDataStr.','.$disMonthInfo->getMonthMoney;
    		$disTotalMoney = $disTotalMoney + $disMonthInfo->getMonthMoney;
    	}
    	$monthDataStr = substr($monthDataStr, 1);


    	$content->row(function ($row) use($year, $monthArrayStr, $monthDataStr, $disTotalMoney) {

            $json = "option = {
    title: {
        text: '所得分销金额总计：{$disTotalMoney}'
    },
    tooltip: {
        trigger: 'axis'
    },
    legend: {
        data:['统计']
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    toolbox: {
        feature: {
            saveAsImage: {}
        }
    },
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [{$monthArrayStr}]
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            name:'{$year}',
            type:'line',
            stack: '每月分销总计',
            data:[{$monthDataStr}]
        }
    ]
};
";


			$echarts = new Echarts('', '');
//			$echarts->setStyle('height:450px;width:100%;');
			$echarts->setDirectJson($json);

            $row->column(12, new Box("{$year}年分销折线图", $echarts));

        });
		/////////////////////////////////////////////////////////////////////////////////
		
		$beginDay = $month.'-01';
		$endDay = $month.'-31';
		//$disDayCount = $Distribution->getDisCount($sId, $userCode, $beginDay, $endDay);
		//print_r(json_encode($disDayCount));exit;
		$disList = $Distribution->getDisListForCount($sId, $userCode, $beginDay, $endDay);
		
		foreach($disList as $disInfo){
			if (isset($disInfo->dbCustomerUid)){
				$userInfo = $Common->getUserInfoWithCache($sId, $disInfo->dbCustomerUid);
				$disInfo->userName0 = $userInfo->userName;
				$disInfo->alName0 = $userInfo->alName;
			} else {
				$disInfo->userName0 = '';
				$disInfo->alName0 = '';
			}
			if (isset($disInfo->uId)){
				$userInfo = $Common->getUserInfoWithCache($sId, $disInfo->uId);
				$disInfo->userName1 = $userInfo->userName;
				$disInfo->alName1 = $userInfo->alName;
			} else {
				$disInfo->userName1 = '';
				$disInfo->alName1 = '';
			}
			if (isset($disInfo->duParentUid)){
				$userInfo = $Common->getUserInfoWithCache($sId, $disInfo->duParentUid);
				$disInfo->userName2 = $userInfo->userName;
				$disInfo->alName2 = $userInfo->alName;
			} else {
				$disInfo->userName2 = '';
				$disInfo->alName2 = '';
			}
			if (isset($disInfo->duGrandUid)){
				$userInfo = $Common->getUserInfoWithCache($sId, $disInfo->duGrandUid);
				$disInfo->userName3 = $userInfo->userName;
				$disInfo->alName3 = $userInfo->alName;
			} else {
				$disInfo->userName3 = '';
				$disInfo->alName3 = '';
			}
		}
//print_r(json_encode($disList));exit;
		
		$headers = ['ID','分销商品','商品数量','分销金额','购买人','推荐人','返利','推荐人上级','上级返利','推荐人上上级','上上级返利','分销时间'];   
		$showTable = array();
		foreach($disList as $disInfo){
			$disTableData = array();
			array_push($disTableData, $disInfo->dbId);
			array_push($disTableData, $disInfo->dbObjName);
			array_push($disTableData, $disInfo->dbSaleNum);
			if ($disInfo->dbSaleMoney == $disInfo->dbActualMoney){
				array_push($disTableData, $disInfo->dbSaleMoney);
			}else{
				array_push($disTableData, $disInfo->dbSaleMoney."(实际支付：{$disInfo->dbActualMoney})");
			}
			
			array_push($disTableData, $disInfo->userName0."【{$disInfo->alName0}】");
			array_push($disTableData, $disInfo->userName1."【{$disInfo->alName1}】");
			array_push($disTableData, $disInfo->dbSelfMoney);
			array_push($disTableData, $disInfo->userName2."【{$disInfo->alName2}】");
			array_push($disTableData, $disInfo->dbParentMoney);
			array_push($disTableData, $disInfo->userName3."【{$disInfo->alName3}】");
			array_push($disTableData, $disInfo->dbGrandMoney);
			array_push($disTableData, $disInfo->createTime);
			array_push($showTable, $disTableData);
		}
        $rows = $showTable;

        $table1 = new Table($headers, $rows);

        $content->row((new Box('分销列表'.$month, $table1))->style('primary')->solid());

		$content->header($selfInfo->userName.'分销统计');
        $content->description(' ');
    
        return $content;
    }
    
    // 显示销售业绩
    public function showPerformance(Request $request, Content $content){
    	
    	$statsDay = $request->input('statsDay', false);
    	if (!$statsDay){
    		$statsDay = date('Y-m-d', time());
    	}
    	$auCode = $request->input('auCode', false);
    	if (!$auCode){
    		$auCode = Admin::user()->auCode;
    	}
    	
    	$sId = Admin::user()->sId;
    	$Common = new Common();
    	
    	$form = new Form();
        $form->method('get');
        $form->date('statsDay', '统计日期')->default($statsDay);
        $form->disableSubmit();
		$form->disableReset();
		$form->setWidth(6, 4);
		//$content->row($form);
        //$content->row('<button type="button" class="btn bg-olive margin">.btn.bg-olive</button>');
        
        $content->row(function ($row) use($form) {

            $row->column(3, $form);
			$row->column(1, '<button id="btnStatsDay" type="button" class="btn bg-olive margin">确定</button>');
        });
        
        $thisUrl = route("showPerformance");
        $script = <<<EOT

	$("#btnStatsDay").click(function(){
		window.location.href = '{$thisUrl}'+'?auCode={$auCode}&statsDay='+$('#statsDay').val();
	});

EOT;
		Admin::script($script);
        
    	
    	$saleDayList = $Common->getSaleDayList($sId, $statsDay, $auCode);
    	$saleDayTotal = 0;
    	foreach ($saleDayList as $saleDayInfo){
    		$saleDayTotal = $saleDayTotal + $saleDayInfo->sgoSalePrice;
    	}
    	
        $headers = ['ID','商品名称','数量','销售金额','购买人', '记录时间'];
		$showTable = array();
		foreach($saleDayList as $saleDayInfo){
			$disTableData = array();
			array_push($disTableData, $saleDayInfo->sgoId);
			array_push($disTableData, $saleDayInfo->sgName);
			array_push($disTableData, $saleDayInfo->sgoSaleNum);
			array_push($disTableData, $saleDayInfo->sgoSalePrice);
			array_push($disTableData, $saleDayInfo->muNickName);
			array_push($disTableData, $saleDayInfo->createTime);
			array_push($showTable, $disTableData);
		}
        $rows = $showTable;

        $table1 = new Table($headers, $rows);
        /////////////////////////////////////////////////////////////////////////////////////////////////
        
        $serviceDayList = $Common->getServiceDayList($sId, $statsDay, $auCode);
//      print_r(json_encode($serviceDayList));exit;
        $serviceMoneyTotal = 0;
        foreach($serviceDayList as $serviceDayInfo){
        	$serviceMoneyTotal = $serviceMoneyTotal + $serviceDayInfo->sgServiceMoney;
        }
        
        $content->row(function ($row) use($saleDayTotal, $serviceMoneyTotal) {

//			$row->column(4, new InfoBox('总销售额', 'users', 'aqua', false, $saleDayTotal+$serviceMoneyTotal)); // 标题，图标，颜色，链接，数量
			$row->column(4, new InfoBox('产品销售金额', 'users', 'green', false, $saleDayTotal)); // 标题，图标，颜色，链接，数量
			$row->column(4, new InfoBox('服务获取金额', 'users', 'aqua', false, $serviceMoneyTotal)); // 标题，图标，颜色，链接，数量
        });
        
        
        $headers = ['ID','卡项名称', '客户姓名', '服务人', '服务项目', '服务费用', '是否已结算费用', '记录时间', '记录人', '记录时间'];
		$showTable = array();
		foreach($serviceDayList as $serviceDayInfo){
			$disTableData = array();
			array_push($disTableData, $serviceDayInfo->sclId);
			array_push($disTableData, $serviceDayInfo->sgName);
			array_push($disTableData, $serviceDayInfo->muNickName);
			array_push($disTableData, $serviceDayInfo->name);
			array_push($disTableData, $serviceDayInfo->sclParts);
			array_push($disTableData, $serviceDayInfo->sgServiceMoney);
			if ($serviceDayInfo->sclIsGetTip == 0){
				array_push($disTableData, '<span class="label label-danger">否</span>');
			}else{
				array_push($disTableData, '<span class="label label-success">是</span>');
			}
			array_push($disTableData, $serviceDayInfo->sclParts);
			array_push($disTableData, $serviceDayInfo->createUser);
			array_push($disTableData, $serviceDayInfo->createTime);
			array_push($showTable, $disTableData);
		}
        $rows = $showTable;

        $table2 = new Table($headers, $rows);

        $content->header('我的业绩');
		$content->description($statsDay);
        $content->row((new Box('商品销售'.$statsDay, $table1))->style('warning')->solid());
        $content->row((new Box('卡项服务'.$statsDay, $table2))->style('primary')->solid());
        
        return $content;
    }
}

